<?php
/**
 * Created by PhpStorm.
 * User: 69548
 * Date: 2018/8/17
 * Time: 15:16
 */

namespace app\wap\controller;
use app\api\controller\OssController;
use app\api\controller\Standard;
use app\api\model\Standard as SDModel;
use app\api\model\GroupToursLine;
use app\wap\model\Goods as M;
use app\api\controller\FareGoods as F;
use think\Db;
use think\db\Expression;
use think\Log;
use app\api\controller\Viator;
use app\api\controller\KbxOther;
use app\admin\model\GeoHash;
use think\Cache;
use app\admin\model\Theme as TModel;
use think\Request;

class Goods extends Collection
{
    public $member_pcode;
    public function _initialize()
    {
        header('Access-Control-Allow-Origin:*');
        $uid=input('uid');
        $member_id=input('member_id');
        if  (!empty($uid)){
            $this->member_pcode=  $uid;
            $uids=db('member')->where('member_id',$uid)->find();
            if (!empty($member_id) && $uid != $member_id && $uids['member_pcode'] != $member_id ){
                db('member')->where('member_id',$member_id)->update([
                    'member_pcode'=> $uid
                ]);
            }
        }
    }

    //套餐时间选择
    public function interval()
    {
        if (!request()->isPost()){
            $shu = [
                'code'  => 101,
                'msg'   => '请求非法',
            ];
            return json($shu);
        }

        $post = request()->post();
        $goods_id = $post['goods_id'];

        $exchange= db('exchange')->where('currency_code',"USD")->find();//汇率
        $goods = db('goods')->where('goods_id', $goods_id)->find();

        //检查商品类型
        if(!empty($goods['standard_pro'])){
            if($goods['channel_source']=='fareharbor'){
                $sell_rate = db("viator_discount")->where(['id'=>2,'status'=>1])->find();
                $faregoods = db("fareharbor_goods")->find($goods['source_id']);
                if(empty($faregoods)){
                    return json(['code'=>0,'msg'=>'ko','data'=>[]]);
                }
                $company = $faregoods['company'];
                $item = $faregoods['item_id'];
                $specs = (new F())->getItemSpecsList($company,$item);
                if(!empty($specs)){
                    foreach ($specs as $key=>$value){
                        $specs[$key]['min_price'] = ceil($value['min_price']*$exchange['exchange_rate']*$sell_rate['discount_num']*100)/100;
                    }
                }
                $data = [
                    'riqijiage'=>$specs,
                    'goods_id'=>$item,
                    'typesource'=>'fareharbor',
                ];
                return json(['code'=>0,'msg'=>'ko','data'=>$data]);
            }else{

            }
        }

//        $datas = cache($goods_id.'rl');//判断是否存在缓存
//        if (!empty($datas) || $datas != false){
//            if(!empty($goods['code']) && $goods['show']== 2){
//                //Viator跳过
//            }else{
//                $shu=[
//                    'code'=>0,
//                    'msg'=>'ok',
//                    'data'=>$datas
//                ];
//                return json($shu);
//            }
//        }

        if (!empty($post['member_id'])){
            $discoun_per_arr = $this->get_discoun_per($post['member_id']);//获取折扣集
            //该类型商品的折扣率
            $discoun_per = isset($discoun_per_arr[$goods['classify_id']]) ? $discoun_per_arr[$goods['classify_id']] : '';
        }

        if (empty($goods)) {
            $shu = [
                'code'  => 101,
                'msg'   => '查询失败商品不存在',
            ];
            echo json_encode($shu);
            die();
        }

        if(!empty($goods['code']) && $goods['show']== 2){
            //获取viator的折扣
            $discoun_num=1;
            $discoun_viator=Db::name('viator_discount')->where(['id'=>1,'status'=>1])->find();
            if(!empty($discoun_viator)){
                $discoun_num = $discoun_viator['discount_num'];
            }
            $data=[];
            $d=[];
            $data1= cache($goods['code'].'price');
            if(empty($data1)){
                $data['riqijiage']='';
            }else{
                //最后一项为数字代表月份 如果是数组就删除 否则删除
                if(!is_array(end($data1))) array_pop($data1);
                foreach ($data1 as $s=>$value){
                    foreach ($value as $k=>$v) {
                        $jia = [];
                        foreach ($v['ageBands'] as $k_a=>$v_a) {
                            if($v_a['price']>0){
                                $min=$v_a['price'];
                                $jia[]=ceil($min*$exchange['exchange_rate']*$discoun_num*100)/100;
                            }
                        }

                        $min_price = min($jia);
                        if (!empty($discoun_per)){
                            $min_price = ceil($discoun_per*$min_price*100)/100;
                        }
                        $d[$v['bookingDate']][] = ['shijian'=>$v['bookingDate'],'min_price'=>$min_price];
                    }
                }
                foreach ($d as $key=>$value){
                    $dateArr = [];
                    $dateArr['number'] = 999;
                    $dateArr['time'] = $key;
                    $jiaGe = [];
                    foreach ($value as $k=>$v) {
                        $jiaGe[] = $v['min_price'];
                    }
                    $dateArr['min_price'] = min($jiaGe);
                    $data['riqijiage'][]=$dateArr;
                }
            }
            $data['goods_id']   = $goods_id;
            $data['typesource']='viator';
            $shu=[
                'code'=>0,
                'msg'=>'ko',
                'data'=>$data
            ];
            return json($shu);
        }

        $endtime = '';
        //获取10个月后的月底
        $btime  = strtotime(date('Y-m-'.date("t",strtotime("+10 month")),strtotime("+10 month")));

        //判断商品售卖时间是否大于10个月后的月底
        if ($btime > $goods['endtime']) {
            $endtime = date('Y-m-d', $goods['endtime']);
        } else {
            $endtime = date('Y-m-d', $btime);
        }
        $pos    = [];
        $data   = [];
        $starttime = $goods['starttime'] > time()?$goods['starttime']:time();
        $starttime = date("Y-m-d",$starttime);

        //产品价格替换
        $product_price_exists = 0;//是否存在产品价格
        //存在产品时
        if(!empty($goods['goods_tcode']) && $goods['goods_tcode']!==''){
            $product = db("product")->where("item_num",$goods['goods_tcode'])->field("id,currency,price_section,new_price_flag,base_price_mode")->find();
            if(!empty($product)){
                if(!empty($product['base_price_mode'])){
                    $product_price_exists = 2;
                }elseif(!empty($product['new_price_flag'])){
                    $product_price_exists = 1;
                }
            }
        }

        if($product_price_exists==2){
            $person = db("product_base_dailyprice pd")
                ->join('product_base_specs ps','ps.id=pd.specs_id','left')
                ->where(["pd.product_id"=>$product['id'],"pd.time"=>['between',[$starttime,$endtime]]])
                ->field("pd.product_id,pd.price as person_price,pd.num as person_num,pd.time")
                ->select();
            //关联产品的价格问题
            if(!empty($product['currency']) && $exchangeRate = db('exchange')->where("currency_code",$product['currency'])->find()){
                //默认人民币汇率
                if(!empty($exchangeRate['exchange_rate'])){
                    foreach ($person as $key=>$value){
                        $person[$key]['person_price'] = ceil(round($value['person_price'])*$exchangeRate['exchange_rate']);
                    }
                }
            }
        }elseif($product_price_exists==1){
            $person = db("product_dailyprice")
                ->where(["product_id"=>$product['id'],"time"=>['between',[$starttime,$endtime]]])
                ->field("product_id,price as person_price,num as person_num,time")
                ->select();
        }else{
            $person = db("personday")
                ->where(["goods_id"=>$goods_id,"time"=>['between',[$starttime,$endtime]]])
                ->field("person_price,goods_id,person_num,time")
                ->select();
//            $person = Db::query("SELECT person_price,goods_id,person_num,`time` FROM `tplay_personday`  WHERE  `goods_id` = $goods_id  AND `time` BETWEEN '".$starttime."' AND '".$endtime."'");
        }
        if (empty($person)){
            $shu = [
                'code'  => 101,
                'msg'   => '商品暂未套餐配置',
            ];
            echo json_encode($shu);
            die();
        }else{
            $persondays = [];
            $everyday = array_column($person,"time");
            //循环所有时间的规格
            foreach ($person as $v) {
                if (!in_array($v['time'], $pos)) {
                    //获取时间
                    $pos[] = $v['time'];
                    $persondays[$v['time']][] = $v;
                } else {
                    $persondays[$v['time']][] = $v;
                }
            }
            //循环每一天的规格组装价格

            foreach ($persondays as $key => $v) {
                //定义价格和数量
                $person_price   = [];
                $num            = [];
                //循环当天的规格
                foreach ($v as $g) {
                    //价格和数量统计
                    $person_price[] = $g['person_price'];
                    $num[]          = $g['person_num'];

                }
                $min = min($person_price);
                $min_key = array_search(min($person_price),$person_price);
                if (!empty($discoun_per)){
                    $min= ceil($discoun_per*$min*100)/100;
                }


                foreach ($pos as $o => $l) {
                    if ($l == $key) {
                        $data['riqijiage'][] = [
                            'time'      => $l,
                            'min_price' => $min,
                            'number' => $num[$min_key],
                        ];
                    }
                }
            }
            $data['goods_id']   = $goods_id;
            $data['typesource'] = 'myself';

            $shu=[
                'code'=>0,
                'msg'=>'ko',
                'data'=>$data
            ];
            //添加缓存有效期一个月
            Cache::set($goods_id.'rl',$data,new \DateTime(date('Y-m-d H:i:s',strtotime('+1 month'))));
            return json($shu);
        }
    }

    //查询每一天的套餐和规格
    public function spec_person(){
        if (!request()->isPost()){
            $shu = [
                'code'  => 101,
                'msg'   => '请求非法',
            ];
            return json($shu);
        }
        $post = request()->post();

        if (empty($post) || empty($post['goods_id']) || empty($post['time'])) return json(['msg'=>'参数不能为空','code'=>'101']);

        $exchange= db('exchange')->where('currency_code',"USD")->find();//汇率
        $goods = db('goods')->where('goods_id', $post['goods_id'])->find();

        if (!empty($post['member_id'])){
            $discoun_per_arr = $this->get_discoun_per($post['member_id']);//获取折扣集
            //该类型商品的折扣率
            $discoun_per = isset($discoun_per_arr[$goods['classify_id']]) ? $discoun_per_arr[$goods['classify_id']] : '';
        }
        if(!empty($goods['code']) && $goods['show']==2){
            //获取viator的折扣
            $discoun_num=1;
            $discoun_viator=Db::name('viator_discount')->where(['id'=>1,'status'=>1])->find();
            if(!empty($discoun_viator)){
                $discoun_num = $discoun_viator['discount_num'];
            }
            $data  = [];
            $d     = [];
            $data1 = cache($goods['code'].'price');

            //By Suley
            //修改过的自定义套餐名称
            $where_name['code'] = $goods['code'];
            $specsName = db('specsname')->where($where_name)->select();
            $nameArr = array();
            if(!empty($specsName)){
                foreach ($specsName as $k_name=>$v_name){
                    $nameArr[$v_name['grade_code']] = $v_name['new_name'];
                }
            }

            $eto_list=[
                'Adult'   => '成人',
                'Child'   => '儿童',
                'Infant'  => '婴儿',
                'Youth'   => '青年',
                'Senior'  => '老年人',
                '成年人'  => '成年人',
                '儿童'    => '儿童',
                '婴儿'    => '婴儿'
            ];

            if(empty($data1)){
                $d=[];
            }else{
                unset($data1['month_num']);
                foreach ($data1 as $s=>$v){
                    foreach ($v as $key_grade=>$value_grade) {
                        if ($value_grade['bookingDate']==$post['time']){
                            foreach ($value_grade['ageBands'] as $l=>$k){
                                $person_price= ceil($exchange['exchange_rate']*$k['price']*$discoun_num*100)/100;
                                if (!empty($discoun_per)){
                                    $person_price= ceil($discoun_per*$person_price*100)/100;
                                }
                                $description_name = isset($eto_list[$k['description']]) ? $eto_list[$k['description']] : $k['description'];
                                if(isset($nameArr[$s])){
                                    $grade_name = $nameArr[$s];
                                }else{
                                    if($s=='DEFAULT'){
                                        $grade_name = "普通套餐";
                                    }else{
                                        $grade_name = $s;
                                        $goods_type = cache($goods['code'].'type');
                                        foreach ($goods_type as $t_key=>$t_value) {
                                            if($s==$t_value['gradeCode']){
                                                $grade_name = !empty($t_value['specs_name'])?$t_value['specs_name']:$t_value['specs_ename'];
                                            }
                                        }
                                        //为解决Viator商品的套餐名字段更新问题，自动对比增加
                                        $new_grade_code_Arr = explode("~",$s);
                                        $new_s = !empty($new_grade_code_Arr[0]) ? $new_grade_code_Arr[0] : '';
                                        if($new_s!==''){
                                            if(isset($nameArr[$new_s])){
                                                foreach ($goods_type as $t_key=>$t_value) {
                                                    if($s==$t_value['gradeCode']){
                                                        $grade_name = $nameArr[$new_s];
                                                        $new_specs_name = $t_value['specs_name'];
                                                        $p_data = array();
                                                        $p_data['code'] = $goods['code'];
                                                        $p_data['grade_code'] = $s;
                                                        $p_data['specs_name'] = $new_specs_name;
                                                        $p_data['new_name'] = $grade_name;

                                                        //防止重复插入
                                                        $p_specsname = db("specsname")->where("grade_code",$s)->find();
                                                        if(empty($p_specsname)){
                                                            db("specsname")->insert($p_data);
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                $d[$grade_name][]=[
                                    "person_id"=>$k['bandId'],
                                    "gradeCode"=>$s,
                                    "person_price"=>$person_price,
                                    "person_num"=>999,
                                    "inc_order_num"=>1,
                                    "person_name"=>$k['age'].'岁'.$description_name,
                                    "max"=>$k['max'],
                                    "min"=>$k['min'],
                                ];
                            }
                            break;
                        }
                    }
                }
            }

            foreach ($d as $k=>$v) {
                $a['specs_id'] = '9999999999';
                $a['specs_name'] = $k;
                $a['person'] = $v;
                $a['gradeCode'] = $v[0]['gradeCode'];
                $data['specs'][] = $a;
            }

            $data['typesource']='viator';
            $shu=[
                'code'  => 0,
                'msg'   => 'ko',
                'data'  => $data
            ];

            return json($shu);die;
        }

        //检查fareharbor类型
        if(!empty($goods['standard_pro'])){
            if($goods['channel_source']=='fareharbor'){
                $faregoods = db("fareharbor_goods")->find($goods['source_id']);
                if(empty($faregoods)){
                    return json(['code'=>0,'msg'=>'ko','data'=>[]]);
                }
                $company = $faregoods['company'];
                $item = $faregoods['item_id'];
                $date = $post['time'];
                $specs = (new F())->specsOneItem($company,$item,$date);
                $specsName = db('faregoods_specname')->where('item_id',$item)->select();
                if(!empty($specsName)){
                    $specsEnName = array_column($specsName,'en_name');
                }else{
                    $specsEnName = [];
                }
                //翻译名称
                foreach ($specs as $i=>$s){
                    foreach ($s['person'] as $x=>$p){
                        if(array_search($p['person_name'],$specsEnName)!==false){
                            $cn_name = $specsName[array_search($p['person_name'],$specsEnName)]['ch_name'];
                        }else{
                            $cn_name = $p['person_name'];
                        }
                        $specs[$i]['person'][$x]['person_name'] = $cn_name;
                    }
                }
                $data = [
                    'specs'=>$specs,
                    'typesource'=>'fareharbor'
                ];
                return json(['code'=>0,'msg'=>'ko','data'=>$data]);
            }else{

            }
        }

        $where=[];
        $where['goods_id']  = $post['goods_id'];
        $where['time']      = $post['time'];

        //产品价格替换
        $product_id = '';
        $product_price_exists = 0;//是否存在产品价格
        //存在产品时
        if(!empty($goods['goods_tcode']) && $goods['goods_tcode']!==''){
            $product = db("product")->where("item_num",$goods['goods_tcode'])->field("id,currency,price_section,new_price_flag,base_price_mode")->find();
            if(!empty($product)){
                $product_id = $product['id'];
                if(!empty($product['base_price_mode'])){
                    $product_price_exists = 2;
                }elseif(!empty($product['new_price_flag'])){
                    $product_price_exists = 1;
                }
            }
        }

        if($product_price_exists==2){
            $personday =  db('product_base_dailyprice pd')
                ->join('product_base_specs ps','ps.id=pd.specs_id','left')
                ->where("pd.product_id",$product['id'])
                ->where("pd.time",$post['time'])
                ->field("pd.*,pd.id,pd.name as person_name,pd.num as person_num,pd.specs_id as person_id,pd.price as person_price,pd.package_id as specs_id")
                ->select();
            //关联产品的价格问题
            $exchange_rate = 1;
            if(!empty($product['currency']) && $exchangeRate = db('exchange')->where("currency_code",$product['currency'])->find()){
                $exchange_rate = $exchangeRate['exchange_rate']??$exchange_rate;
            }
            foreach ($personday as $k=>$v){
                $personday[$k]['person_price'] = $exchange_rate>1?ceil(round($v['person_price'])*$exchange_rate):round($v['person_price']);
            }
            //获取套餐
            $specs = db('product_base_package')
                ->where(['product_id'=>$product['id']])
                ->where('status',1)
                ->field('id as specs_id,name as specs_name')
                ->select();
        }elseif($product_price_exists==1){
            //获取规格
            $personday =  db('product_dailyprice')
                ->where("product_id",$product_id)
                ->where("time",$post['time'])
                ->field("*,id,name as person_name,num as person_num,specs_id as person_id,price as person_price,package_id as specs_id")
                ->select();
            //获取套餐
            $specs = db('product_package')
                ->where(['product_id'=>$product_id])
                ->where('status',1)
                ->field('id as specs_id,name as specs_name')
                ->select();
        }else{
            //获取规格
            $personday =  db('personday')->where($where)->select();
            //获取套餐
            $specs = db('specs')
                ->where(['goods_id'=>$post['goods_id']])
                ->where('specs_status',1)
                ->where('specs_types', 1)
                ->field('specs_id,specs_name')
                ->select();
        }

        foreach ($specs as $k => &$b){
            $specs[$k]['person'] = [];
            foreach ($personday as $v){
                if ($v['specs_id'] == $b['specs_id']){
                    unset($v['specs_id']);
                    unset($v['goods_id']);
                    unset($v['time']);
                    $v['person_id'] = $v['id'];
                    unset($v['id']);

                    if (!empty($discoun_per)){
                        $v['person_price'] = ceil($discoun_per*$v['person_price']*100)/100;
                    }
                    $specs[$k]['person'][]  = $v;
                    $specs[$k]['gradeCode'] = "";
                }
            }
            if(empty($specs[$k]['person'])){
                unset($specs[$k]);
            }
        }
        $data = [];
        $data['specs'] =   $specs;
        $data['typesource'] = 'myself';
        $shu=[
            'code'  => 0,
            'msg'   => 'ko',
            'data'  => $data
        ];
        return json($shu);
    }

    //列表数据
    public function index(){
        $post= request()->post();
        $m= new M();

        //总页数
        $exchange= db('exchange')->where('currency_code',"USD")->find();//汇率
        $city_id =  $post['city_id'];
        $classify_id = !empty($post['classify_id'])?$post['classify_id']:[];
        $tag_id =  !empty($post['tag_id'])?$post['tag_id']:0;
        //天数
        $days =  !empty($post['days'])?$post['days']:[];
        //服务语音
        $service_languages =  !empty($post['service_languages'])?$post['service_languages']:[];
        //价格区间
        $s_min_price =  !empty($post['min_price'])?$post['min_price']:'';
        $s_max_price =  !empty($post['max_price'])?$post['max_price']:'';
        //页码
        $pagenum=!empty($post['pagenum'])?$post['pagenum']:1;
        //每页显示数量
        $pagelimit=!empty($post['pagelimit'])?$post['pagelimit']:20;
        $member_id=!empty($post['member_id'])? $post['member_id']:0;//用户id
        $recommend=!empty($post['recommend'])?$post['recommend']:0;
        $sort= !empty($post['sort'])?$post['sort']:0;
        $popular=!empty($post['popular'])?$post['popular']:0;

        if (empty($city_id)) return json_encode(['code'=>101,'msg'=>'参数错误',]);
        if($recommend==1) $map['g.recommend']=1;
        if($popular==1) $map['g.popular']=1;


        if (!empty($tag_id)){
            $map['g.tag_id']=['like','%'.$tag_id.'%'];
        }
        $discoun_per='';
        $discoun_per_arr=array();
        if (!empty($member_id)){
            $discoun_per_arr = $this->get_discoun_per($member_id);//获取折扣集
        }

        $city= db('city')->where('id',$city_id)->find();
        $map['g.goods_status']='1';
        //是否拼团产品 拼团不显示
        $map['g.is_group']='0';
        $city_function = function ($query) use ($city) {
            $query->where('g.city_id','eq',$city['id'])
//                ->whereor('g.city_id','eq',$city['destid'])
                ->whereor("find_in_set('{$city['id']}',g.belong_city)")
                ->whereor("g.belong_city = 999999");
        };
        $isJoinProductModel = false;
        //类型
        if (!empty($classify_id)){
            $map['g.classify_id'] = ['in',$classify_id];
        }
        //服务语言
        if(!empty($service_languages)){
            $lang_where = [];
            //是否包含中文
            if(in_array(2,$service_languages)) $lang_where[] = "0";
            if(in_array(1,$service_languages)){
                $lang_where[] = "1";
                //viator产品都属于英文服务
                foreach ($lang_where as $l_k=>$l_v){
                    $lang_where[$l_k] = "'".intval($l_v)."'";
                }
                //viator产品都属于英文服务
                $lang_where = implode(',',$lang_where);
                $map['service_language'] = ['exp',new Expression(' in ('.$lang_where.') or g.`show` = 2')];
            }else{
                $map['p.service_language'] = ['in',$lang_where];
            }
            $isJoinProductModel = true;
        }
        //行程天数
        if(!empty($days)){
            $days_where = [];
            foreach ($days as $days_value){
                $days_where[] = $days_value<3?'p.days='.$days_value:'p.days>=3';
            }
            $days_where_str = empty($days_where)?'':implode(' or ',$days_where);
            if(!empty($days_where_str)){
                $days_where_str = substr($days_where_str,6);
                $map['p.days'] = ['exp',new Expression($days_where_str)];
            }

            $isJoinProductModel = true;
        }
        //价格区间筛选 取交集
        if(!empty($s_min_price)){
            $map['g.min_price'] = ['egt',$s_min_price];
        }
        if(!empty($s_max_price)){
            $map['g.max_price'] = ['elt',$s_max_price];
        }
        //需要关联产品
        if($isJoinProductModel){
            $map['g.goods_tcode'] = ['exp', new Expression('is not null and g.goods_tcode!=""')];
            $totalNum = $m->alias('g')
                ->join('product p','p.item_num=g.goods_tcode','left')
                ->where($city_function)
                ->where($map)
                ->count('g.city_id');
            $date= $m->alias('g')
                ->where($city_function)
                ->where($map)
                ->join('product p','p.item_num=g.goods_tcode','left')
                ->join('classify c','g.classify_id=c.classify_id','left')
                ->join('tag t','t.tag_id=g.goodstag_id','left')
                ->order('g.updatetime desc')
                ->field('g.goods_id as id,g.goods_name as name,g.goods_image,
                              g.small_image as img ,g.classify_id,g.price,
                              g.goods_englishname as eng_name,g.starttime,g.endtime,
                              g.recommend,g.popular,g.updating,g.goodstag_id,g.goodssales,g.invented_sold,
                              g.show,g.price_section,g.standard_pro,g.channel_source,
                              g.source_id,g.goods_tcode,g.min_price,g.max_price,g.`show`,
                              c.classify_name,t.tag_name')
                ->order('g.updating desc,g.updatetime desc')
                ->page($pagenum,$pagelimit)
                ->select();
        }else{
            $totalNum=$m->alias('g')
                ->where($city_function)
                ->where($map)
                ->count('g.city_id');

            $date= $m->alias('g')
                ->where($city_function)
                ->where($map)
                ->join('classify c','g.classify_id=c.classify_id','left')
                ->join('tag t','t.tag_id=g.goodstag_id','left')
                ->field('goods_id as id,goods_name as name,goods_image,
                small_image as img ,g.classify_id,price,goods_englishname as eng_name,
                starttime,endtime,recommend,popular,updating,goodstag_id,goodssales,g.invented_sold,
                show,price_section,standard_pro,channel_source,source_id,goods_tcode,
                min_price,max_price,`show`,c.classify_name,t.tag_name')
                ->order('updating desc,g.updatetime desc')
                ->page($pagenum,$pagelimit)
                ->select();
        }
        //总页数
        $totalPage=ceil($totalNum/$pagelimit);
        $collection=0;
        //初始化
        $result = [
            'pagenum'=>$pagenum,
            'pagelimit'=>$pagelimit,
            'totalpage'=>$totalPage,
            'totalnum'=>$totalNum,
            'goods'=>[]
        ];
        //获取viator的折扣
        $discoun_viator = db('viator_discount')->where(['id'=>1,'status'=>1])->find();
        $discoun_num = !empty($discoun_viator)?$discoun_viator['discount_num']:1;
        if (empty($date)) return json_encode(['code'=>101,'msg'=>'暂无更多数据']);

        foreach ($date as $k=>$v){
            //产品价格替换
            $product_price_exists = 0;//是否存在产品价格
            //存在产品时
            if(!empty($v['goods_tcode']) && $v['goods_tcode']!==''){
                $product = db("product")->where("item_num",$v['goods_tcode'])->field("id,price_section,currency,new_price_flag,base_price_mode,min_price,max_price")->find();
                if(!empty($product['base_price_mode'])){
                    $dailyprice = db("product_base_dailyprice")->where("product_id",$product['id'])->field('max(price) as max_price,min(price) as min_price')->find();
                    if(!empty($dailyprice)){
                        $v['price_section'] = $product['price_section'];
                        $v['min_price'] = $dailyprice['min_price']??0;
                        $v['max_price'] = $dailyprice['max_price']??0;
                        $product_price_exists = 2;//存在产品设置价格
                    }
                }elseif(!empty($product['new_price_flag'])){
                    $dailyprice = db("product_dailyprice")->where("product_id",$product['id'])->field('max(price) as max_price,min(price) as min_price')->find();
                    if(!empty($dailyprice)){
                    $v['price_section'] = $product['price_section'];
                        $v['min_price'] = $dailyprice['min_price']??0;
                        $v['max_price'] = $dailyprice['max_price']??0;
                        $product_price_exists = 1;//存在产品设置价格
                    }
                }
            }

            $goods_classify_id = $v['classify_id'];
            //该类型商品的会员折扣率
            if(!empty($discoun_per_arr)){
                $discoun_per = isset($discoun_per_arr[$goods_classify_id]) ? $discoun_per_arr[$goods_classify_id] : '';
            }
            $old_price = $new_price = '';
            if($v['channel_source']=='fareharbor'){
                // fareharbor商品价格
                $old_price = '';
                $new_price = $v['price_section'];
            }elseif(!empty($v['price'])){
                //viator 商品折扣判断
                if($v['show'] == 2 && !empty($discoun_num)){
                    $v['price']= $v['price'] * $discoun_num;
                }
                $old_price = '';
                $new_price = ceil($v['price']*$exchange['exchange_rate']);
                if(!empty($discoun_per)){
                    $old_price = ceil($v['price']*$exchange['exchange_rate']);
                    $new_price = ceil($discoun_per*$new_price);
                }
            }else{
                /*
                 *  2019-11-15
                 *  产品价格替代商品价格
                 *  by suley
                */
                if($product_price_exists > 0){//取用产品价格
                    $price_section = $v['price_section'];
                    $price_section_arr = explode("~",$price_section);
                    $max_price = !empty($v['max_price'])?$v['max_price']:$price_section_arr[1];
                    $min_price = !empty($v['min_price'])?$v['min_price']:$price_section_arr[0];
                    //viator 商品折扣判断
                    if($v['show'] == 2 && !empty($discoun_num)){
                        $max_price = ceil($discoun_num * $max_price);
                        $min_price = ceil($discoun_num * $min_price);
                    }
                    if (!empty($discoun_per)){
                        if ($max_price==$min_price  || $min_price=='0.00'){
                            $old_price = $max_price;
                            $new_price = ceil($max_price*$discoun_per);
                        }else{
                            $old_price = $min_price.'~'.$max_price;
                            $new_price=  ceil($min_price*$discoun_per).'~'.ceil($max_price*$discoun_per);
                        }
                    }else{
                        $old_price = '';
                        $new_price=  $min_price.'~'.$max_price;
                        if ($min_price==$max_price || $min_price=='0.00'){
                            $new_price = ceil($max_price);
                        }
                    }
                }else{
                    $price_section_arr = explode("~",$v['price_section']);
                    if (!empty($price_section_arr)){
                        $max_price = !empty($v['max_price'])?$v['max_price']:($price_section_arr[1]??($price_section_arr[0]??'0.00'));
                        $min_price = !empty($v['min_price'])?$v['min_price']:($price_section_arr[0]??'0.00');
                        //viator 商品折扣判断
                        if($v['show'] == 2 && !empty($discoun_num)){
                            $max_price = ceil($discoun_num * $max_price);
                            $min_price = ceil($discoun_num * $min_price);
                        }
                        if (!empty($discoun_per)){
                            $old_price=$max_price.'~'.$min_price;
                            $new_price=  ceil($max_price*$discoun_per).'~'.ceil($max_price*$discoun_per);
                            if ($max_price==$min_price  || $min_price=='0.00'){
                                $new_price=ceil($min_price*$discoun_per);
                                $old_price=$max_price;
                            }
                        }else{
                            $old_price='';
                            $new_price=  $min_price.'~'.$max_price;
                            if ($max_price==$min_price || $min_price=='0.00'){
                                $new_price=ceil($max_price);
                            }
                        }
                    }
                }
            }
            //是否收藏
            if (!empty($member_id)){
                $collection=db('collection')->where('goods_id',$v['id'])
                    ->where(['collection_types'=>1,'member_id'=>$member_id])
                    ->count();
            }
            //获取压缩图片地址
            if (!empty($v['img'])){
                $image = array_filter(explode(',',$v['img']));
            }else{
                $image = array_filter(explode(',',$v['goods_image']));
            }
            $image=array_values($image);
            $image_url = '';
            if(!empty($image[0])){
                $image_url = (new OssController())->getOssThumbImg($image[0]);
                $image_url = (new GroupToursLine())->replaceOssImgDomain($image_url);
            }
            //获取最早售卖时间
            $zuizao='未知';
            $now = time();
            if ($now > $v['starttime'] && $now < $v['endtime'] ){
                    $zuizao='今天';
            }elseif($now <= $v['starttime']){
                $zuizao=date('m-d',$v['starttime']);
            }


            //评论数
            $comment_num = db("comment")->where(['goods_id'=>$v['id']])->count();
            //增加天数显示
            $days = 0;
            $days_str = '';
            if(!empty($v['goods_tcode'])){
                $linkProductInfo = db('product')
                    ->where('item_num',$v['goods_tcode'])
                    ->field('days')->find();
                if(!empty($linkProductInfo['days'])){
                    $days = $linkProductInfo['days'];
                    $days_str = $linkProductInfo['days'].'日';
                }
            }
            if(!empty($new_price) || !empty($old_price)){
                $result['goods'][] = [
                    'goods_id'=>$v['id'],
                    'recommend'=>$v['recommend'],
                    'popular'=>$v['popular'],
                    'name'=>$v['name'],
                    'jiage'=>$new_price,
                    'image'     =>$image_url,
                    'eng_name'=>$v['eng_name'],
                    'zuizao'=>$zuizao,
                    'collection'=>$collection,
                    'yuanjia'=>$old_price,
                    'updating'=>$v['updating'],
                    'comment_num'=>$comment_num,
                    'order_num'=>$v['goodssales'] + $v['invented_sold'],
                    'ifytype'   =>$v['classify_name'],  //水印内容
                    'goodstag'  =>$v['tag_name'],   //商品标签
                    'days'=>$days,//行程天数
                    'days_str'=>$days_str, //行程天数显示
                    'is_viator'=>$v['show']==2?true:false, //是否为viator
                ];
            }
        }

        if ($sort!=0){
            $result = $this->insertSort($result,$sort);
        }
        //$d['goods']=array_slice($d['goods'],$pages,$pagelimit);
        $res = [
            'code'=>0,
            'msg'=>'请求成功',
            'data'=> $result,
            'member_pcode'=>$this->member_pcode
        ];

        return json_encode($res);
    }

    //商品列表价格排序方法 $c=1 从小到大 2从大到小
    public function insertSort($arr,$c) {
        $len=count($arr['goods']);
        if ($c=='1'){
            for($i=1; $i<$len; $i++ ) {
                $tmp = $arr['goods'][$i]['jiage'];
                $dmp = explode('~',$tmp);
                if (!empty($dmp[1])){
                    $dmp=floor($dmp[1]);
                }else{
                    $dmp=floor($dmp[0]);
                }
                //内层循环控制，比较并插入
                for($j=$i-1;$j>=0;$j--) {
                    $tmp1 = $arr['goods'][$j]['jiage'];
                    $dmp1 = explode('~',$tmp1);
                    if (!empty($dmp1[1])){
                        $dmp1=floor($dmp1[1]);
                    }else{
                        $dmp1=floor($dmp1[0]);
                    }
                    if((int)$dmp < (int)$dmp1) {
                        $tm= $arr['goods'][$j+1];
                        //发现插入的元素要小，交换位置，将后边的元素与前面的元素互换
                        $arr['goods'][$j+1] = $arr['goods'][$j];
                        $arr['goods'][$j] = $tm;
                    }
                }
            }
            return $arr;
        }else if ($c=='2'){
            for($i=1; $i<$len; $i++ ) {
                $tmp = $arr['goods'][$i]['jiage'];
                $dmp = explode('~',$tmp);
                if (!empty($dmp[1])){
                    $dmp=floor($dmp[1]);
                }else{
                    $dmp=floor($dmp[0]);
                }

                //内层循环控制，比较并插入
                for($j=$i-1;$j>=0;$j--) {
                    $tmp1 = $arr['goods'][$j]['jiage'];
                    $dmp1 = explode('~',$tmp1);
                    if (!empty($dmp1[1])){
                        $dmp1=floor($dmp1[1]);
                    }else{
                        $dmp1=floor($dmp1[0]);
                    }

                    if(floor($dmp) > floor($dmp1)) {
                        $tm= $arr['goods'][$j+1];
                        //发现插入的元素要小，交换位置，将后边的元素与前面的元素互换
                        $arr['goods'][$j+1] = $arr['goods'][$j];
                        $arr['goods'][$j] = $tm;
                    }
                }
            }
            return $arr;
        }
    }

    //商品详情页面
    public function details(){
        $goods_id=  input('goods_id');
        $member_id=  input('member_id');
        $data=[];
        $yuanjia='';

        $log[]=[
            '查询details：$member_id'=>$member_id,
        ];
        Log::record($log);

        $exchange= db('exchange')->where('currency_code',"USD")->find();//汇率
        $m = new M();

        $goods= $m->alias('a')
            ->join('goodstag g','a.goodstag_id=g.tag_id','left')
            ->field('a.*,g.tag_name')
            ->where('goods_id',$goods_id)->find();
        if (!empty($member_id)){
            $discoun_per_arr = $this->get_discoun_per($member_id);//获取折扣集
            //该类型商品的折扣率
            $discoun_per = isset($discoun_per_arr[$goods['classify_id']]) ? $discoun_per_arr[$goods['classify_id']] : '';
        }

        //获取viator的折扣
        $discoun_num='';
        if($goods['show'] == 2){
            $discoun_viator=Db::name('viator_discount')->where(['id'=>1,'status'=>1])->find();
            if(!empty($discoun_viator)){
                $discoun_num = $discoun_viator['discount_num'];
            }
        }

        //获取城市
        $city=db('city')->where('id',$goods['city_id'])->field('name,id as city_id,groupid')->find();
        //获取tag  标签
        $len= strlen($goods['tag_id']);
        $tag='';
        if ($len>1){
            $tag_id=explode(',',$goods['tag_id']);
            foreach ($tag_id as $t){
                $tag1=model('Tag')->where('tag_id',$t)->field('tag_id,tag_name')->find();//tag 标签
                $tag[]=[
                    'tag_id'=>$tag1['tag_id'],
                    'tag_name'=>$tag1['tag_name'],
                ];
            }
        }else if($len>0){
            $tag=model('Tag')->where('tag_id',$goods['tag_id'])->field('tag_id,tag_name')->select();//tag 标签
        }

        $zhekou='';
        $yuanjia='';
        if(!empty($goods['price'])){
            //viator 商品折扣判断
            if($goods['show'] == 2 && !empty($discoun_num)){
                $goods['price']=$goods['price']*$discoun_num;
            }

            $zhekou=ceil($goods['price']*$exchange['exchange_rate']*100)/100;
            $yuanjia='';
            if (!empty($discoun_per)){
                $zhekou=ceil( $discoun_per*$zhekou*100)/100;
                $yuanjia=ceil($goods['price']*$exchange['exchange_rate']*100)/100;
            }
        }elseif($goods['standard_pro']==1 && $goods['channel_source']=='fareharbor'){
            //折扣价
            $discoun_fareharbor = db("viator_discount")->where("id=2 and status=1")->find();
            $discoun_num = $discoun_fareharbor['discount_num'];
            //折扣价为美元价
            $zhekou = $goods['price_section'];
            $yuanjia = '';
        }else {
            //产品价格替换
            $product_price_exists = 0;//是否存在产品价格
            //存在产品时
            if(!empty($goods['goods_tcode']) && $goods['goods_tcode']!==''){
                $product = db("product")->where("item_num",$goods['goods_tcode'])->field("id,currency,price_section,new_price_flag,base_price_mode")->find();
                if(!empty($product)){
                    if(!empty($product['base_price_mode'])){
                        $product_price_exists = 2;//存在产品设置基础价格
                    }elseif(!empty($product['new_price_flag'])){
                        $product_price_exists = 1;//存在产品设置价格
                    }
                    if(!empty($product['price_section'])){
                        $goods['price_section'] = $product['price_section'];
                    }
                }
            }

            if($product_price_exists==2 && $goods['show'] == 1){
                $product_cost = db("product_base_dailyprice pd")
                    ->join('product_base_specs ps','ps.id=pd.specs_id','left')
                    ->field("min(pd.price*pd.minorder_num) as minprice,max(pd.price*pd.minorder_num) as maxprice")
                    ->where(['product_id'=>$product['id'],'total_cost'=>['gt',0],'ps.special'=>['lt',1]])
                    ->find();
                $min = round($product_cost['minprice']??0);
                $max = round($product_cost['maxprice']??0);
                //关联产品的价格问题
                if(!empty($product['currency']) && $exchangeRate = db('exchange')->where("currency_code",$product['currency'])->find()){
                    $local_exchange = $exchangeRate['exchange_rate']??1;//默认人民币汇率
                    $min = ceil($min*$local_exchange);
                    $max = ceil($max*$local_exchange);
                }
            }elseif($product_price_exists==1 && $goods['show'] == 1){
                $price_section = $goods['price_section'];
                $price_section_arr = explode("~",$price_section);
                $max= $price_section_arr[1];
                $min= $price_section_arr[0];
            }else{
                $specs = db('Specs')->alias('s')
                    ->where('s.goods_id', $goods_id)
                    ->where('s.specs_status', '1')
                    ->join('Person p', 's.specs_id=p.specs_id')
                    ->where('p.person_status', '1')
                    ->field('p.person_price')
                    ->select();
                $zhekou = '';
                $yuanjia = '';
                if ($specs == false) {
                    $shu = [
                        'code' => 100,
                        'msg' => '啊哦~没有商品数据哦',
                    ];
                    echo json_encode($shu);
                    die;
                }
                //商品价格组装
                if (!empty($specs)) {
                    foreach ($specs as $k => $v) {
                        $price[] = $v['person_price'];
                    }
                    //viator 商品折扣判断
                    if($goods['show'] == 2 && !empty($discoun_num)){
                        $max = ceil(max($price) * $discoun_num*100)/100;
                        $min = ceil(min($price) * $discoun_num*100)/100;
                    }else{
                        if($goods['show'] == 1){
                            if(!empty($goods['price_section'])){
                                $price_section = $goods['price_section'];
                                $price_section_arr = explode("~",$price_section);
                                $max= $price_section_arr[1];
                                $min= $price_section_arr[0];
                            }else{
                                $max = ceil(max($price)*100)/100;
                                $min = ceil(min($price)*100)/100;
                            }
                        }else{
                            $max = ceil(max($price)*100)/100;
                            $min = ceil(min($price)*100)/100;
                        }
                    }
                }
            }

            if (!empty($discoun_per)) {
                $zhekou = ceil(($min * $discoun_per)*100)/100 . '~' . ceil(($max * $discoun_per)*100)/100;
                $yuanjia = $min.'~'.$max;
                if ($max == $min || $min == '0.00') {
                    $zhekou = ceil($max * $discoun_per*100)/100;
                    $yuanjia = $max;
                }
            } else {
                $zhekou = ceil( $min*100)/100 .'~'. ceil($max*100)/100;
                $yuanjia = '';
                if ($max == $min || $min == '0.00') {
                    $zhekou =  $max;
                }
            }
        }


        //猜你喜欢   商品推荐
        $tuijianid = db("goods")
            ->where('city_id',$goods['city_id'])
            ->where('goods_id','NEQ',$goods['goods_id'])
            ->where('goods_status',1)
            ->select();
        $tuijian1='';
        $tuijianjia='';
        $yuanjia1='';
        $tuijian=[];
        if (!empty($tuijianid)){
            if(count($tuijianid)<=4){
                $tuijian= $tuijianid;
            }else{
                shuffle($tuijianid);//对数组进行乱序操作
                $tuijian=array_slice($tuijianid,0,4);//取出乱序后数组前4条数据
            }

            foreach ($tuijian as $k=>$t) {
                if ($t['goods_id'] != $goods['goods_id']) {
                    if(!empty($t['price'])){
                        $yuanjia1='';
                        $tuijianjia=ceil($t['price']*$exchange['exchange_rate']*100)/100;
                        if (!empty($discoun_per)){
                            $yuanjia1=$tuijianjia;
                            $tuijianjia=ceil($tuijianjia* $discoun_per*100)/100;
                        }
                    }else{
                        //产品价格替换
                        $product_price_exists = 0;//是否存在产品价格
                        //存在产品时
                        if(!empty($t['goods_tcode']) && $t['goods_tcode']!==''){
                            $product = db("product")->where("item_num",$t['goods_tcode'])->field("id,price_section")->find();
                            if(!empty($product)){
                                $product_id = $product['id'];
                                $dailyprice = db("product_dailyprice")->where("product_id",$product_id)->find();
                                if(!empty($dailyprice)){
                                    $t['price_section'] = $product['price_section'];
                                    $product_price_exists = 1;//存在产品设置价格
                                }
                            }
                        }

                        if($product_price_exists==1){
                            $price_section_arr = explode("~",$t['price_section']);
                            $max1= $price_section_arr[1];
                            $min1= $price_section_arr[0];
                            $max1 = ceil($max1*100)/100;
                            $min1 = ceil($min1*100)/100;

                            if (!empty($discoun_per)) {
                                $yuanjia1=$min1.'~'.$max1;
                                $tuijianjia = ceil(($min1 * $discoun_per)*100)/100 . '~' . ceil(($max1 * $discoun_per)*100)/100;
                                if ($max1 == $min1 || $min1=='0.00') {
                                    $yuanjia1=$max1;
                                    $tuijianjia = ceil(($max1 * $discoun_per)*100)/100;
                                }
                            } else {
                                $tuijianjia = ceil($min1*100)/100 .'~'.ceil($max1*100)/100;
                                $yuanjia1=$tuijianjia;
                                if ($max1 == $min1 || $min1=='0.00') {
                                    $tuijianjia = ceil($max1*100)/100;
                                    $yuanjia1 = $tuijianjia;
                                }
                            }
                        }else{
                            $specs1 = db('Specs')->alias('s')
                                ->where('s.goods_id', $t['goods_id'])
                                ->where('s.specs_status', '1')
                                ->join('Person p','s.specs_id=p.specs_id')
                                ->where('p.person_status', '1')
                                ->field('p.person_price')
                                ->select();
                            $price1='';
                            if (!empty($specs1)) {
                                foreach ($specs1 as $k => $v) {
                                    $price1[] = $v['person_price'];
                                }
                                $max1 = ceil(max($price1)*100)/100;
                                $min1 = ceil(min($price1)*100)/100;

                                if (!empty($discoun_per)) {
                                    $yuanjia1=$min1.'~'.$max1;
                                    $tuijianjia = ceil(($min1 * $discoun_per)*100)/100 . '~' . ceil(($max1 * $discoun_per)*100)/100;
                                    if ($max1 == $min1 || $min1=='0.00') {
                                        $yuanjia1=$max1;
                                        $tuijianjia = ceil(($max1 * $discoun_per)*100)/100;
                                    }
                                } else {
                                    $tuijianjia = ceil($min1*100)/100 .'~'.ceil($max1*100)/100;
                                    $yuanjia1 = $tuijianjia;
                                    if ($max1 == $min1 || $min1=='0.00') {
                                        $tuijianjia = ceil($max1*100)/100;
                                        $yuanjia1 = $tuijianjia;

                                    }
                                }
                            }
                        }
                    }
                    $imgs = !empty($t['goods_image']) ? explode(',', $t['goods_image']) : '';
                    if (!empty($imgs[1])) {
                        $imgs = $imgs[1];
                    } else {
                        $imgs = !empty($imgs[0])?$imgs[0]:'';
                    }
                    if($t['show']==1){
                        $img_type=1;
                    }else{
                        $img_type=2;
                    }
                    $tuijian1[] = [
                        'goods_id' => $t['goods_id'],
                        'jiage' => $tuijianjia,
                        'yuanjia' => $yuanjia1,
                        'name' => $t['goods_name'],
                        'image' => $imgs,
                        'img_type'=>$img_type
                    ];
                }
            }
        }
        //评论
        $comment=db('comment')
            ->alias('a')
            ->join('member d','a.member_id=d.member_id')
            ->join('attachment b','b.id=d.thumb')
            ->where('a.goods_id',$goods_id)
            ->where('a.comment_status',2)
            ->field('a.content,a.creattime,a.comment_img')
            ->field('a.content,a.creattime,d.member_nickname,b.filepath as touxiang,a.comment_img')
            ->order('a.creattime desc')
            ->limit(3)
            ->select();

        $pinglun=[];
        if (!empty($comment)){
            foreach ($comment as $c){
                if(!empty($c['comment_img'])){
                    $img1= json_decode($c['comment_img']);
                }

                $pinglun[]= [
                    'content'=>$c['content'],
                    'creattime'=>date('Y-m-d H:i:s',$c['creattime']),
                    'member_nickname'=>$c['member_nickname'],
                    'touxiang'=>$c['touxiang'],
                    'img'=>$img1
                ];
            }
        }else{
            $pinglun='';
        }


        //评论数
        $where_comment['goods_id'] = $goods_id;
        $comment_res = Db::name("comment")->where($where_comment)->field("comment_id")->select();
        $comment_num = count($comment_res);

        //图片路径处理
        $image=!empty($goods['goods_image'])?explode(',',$goods['goods_image']):[];
        $image= array_filter($image);
        if ($image!=''){
            $video_show=reset($image);
        }else{
            $image= '';
            $video_show='';
        }

        //视频处理
        $video=!empty($goods['goods_video'])?['src'=>$goods['goods_video'],'img'=>$video_show]:'';

        //最早可购买时间
        $zuizao='';
        if (time()>$goods['starttime'] && time()<$goods['endtime'] ){
            $zuizao='今天';
        }else if(time()<$goods['starttime']){
            $zuizao=date('Y-m-d',$goods['starttime']);
        }else{
            $zuizao='未知';
        }

        $collection=model('Collection')->where('goods_id',$goods['goods_id'])
            ->where('collection_types',1)->where('member_id',$member_id)->find();

        if (!empty($collection)){
            $collection=1;
        }else{
            $collection=0;
        }

        //增加美元/加元价格区间显示     按照商品城市分别展示美元/加元
        if($city['groupid']==48){//美国城市
            $currency_code = "USD";
        }elseif($city['groupid']==51){//加拿大
            $currency_code = "CAD";
        }else{
            $currency_code = "USD";
        }
        $exchangeArr = Db::name("exchange")->where("currency_code",$currency_code)->find();//汇率
        $local_exchange = $exchangeArr['exchange_rate'];//当地汇率    美元/加元

        $yuanjiaArr = explode("~",$yuanjia);
        $zhekouArr = explode("~",$zhekou);

        if(count($yuanjiaArr)>1){
            $foreign_yuanjia_min = ceil(($yuanjiaArr[0]/$local_exchange)*100)/100;
            $foreign_yuanjia_max = ceil(($yuanjiaArr[1]/$local_exchange)*100)/100;
            $foreign_yuanjia = $foreign_yuanjia_min."~".$foreign_yuanjia_max;
        }else{
            $foreign_yuanjia = ceil(($yuanjia/$local_exchange)*100)/100;
            if($foreign_yuanjia==0){
                $foreign_yuanjia = '';
            }
        }

        if(count($zhekouArr)>1){
            $foreign_zhekou_min = ceil(($zhekouArr[0]/$local_exchange)*100)/100;
            $foreign_zhekou_max = ceil(($zhekouArr[1]/$local_exchange)*100)/100;
            $foreign_zhekou = $foreign_zhekou_min."~".$foreign_zhekou_max;
        }else{
            $foreign_zhekou = ceil(($zhekou/$local_exchange)*100)/100;
        }

        //产品副标题
        $standard = db('standard')->where('goods_id',$goods['goods_id'])->find();
        $product = db('product')
            ->field('service_type,net_weight,shelf_life,
            production_date,production_license,storage_conditions,
            edible_methods,executive_standard_no,customer_content,
            assembling_place,activity_duration,activity_person_num,play_ways,
            self_driving_level,vehicle_require,itinerary_summary,self_driving_distance,
            is_text_plan,text_plan,customer_info_config,all_customer_req')
            ->where('item_num',$goods['goods_tcode'])->find();
        $customer_content = !empty($product['customer_content'])?json_decode($product['customer_content'],true):[];
        $featuredProduct = new \ArrayObject();
        $activityInfo = new \ArrayObject();
        $selfDriveInfo = new \ArrayObject();
        $is_text_plan = !empty($product['is_text_plan'])?true:false;
        $textPlan = !empty($product['text_plan'])?$product['text_plan']:'';
        if(!empty($product['service_type'])){
            $orderType = db('service_type')->field('type')->find($product['service_type'])['type']??'';
            if($orderType=='FeaturedProduct'){
                $featuredProduct = [
                    'net_weight'=>$product['net_weight'],
                    'shelf_life'=>$product['shelf_life'],
                    'production_date'=>$product['production_date'],
                    'production_license'=>$product['production_license'],
                    'storage_conditions'=>$product['storage_conditions'],
                    'edible_methods'=>$product['edible_methods'],
                    'executive_standard_no'=>$product['executive_standard_no'],
                ];
            }elseif ($orderType=='StdActivity'){
                $activityInfo = [
                    'assembling_place'=>$product['assembling_place'],
                    'activity_duration'=>$product['activity_duration'],
                    'activity_person_num'=>$product['activity_person_num'],
                    'play_ways'=>$product['play_ways']
                ];
            }elseif ($orderType=='StdSelfDrive'){
                $selfDriveInfo = [
                    'assembling_place'=>$product['assembling_place'],
                    'self_driving_level'=>$product['self_driving_level'],
                    'vehicle_require'=>$product['vehicle_require'],
                    'itinerary_summary'=>$product['itinerary_summary'],
                    'self_driving_distance'=>$product['self_driving_distance'],
                ];
            }
        }
        $data=[
            'goods_id'=>$goods['goods_id'],//商品id
            'orderType'=>$goods['orderType'],//商品订单类型
            'title'=>$goods['goods_name'],//商品中文名
            'collection'=>$collection,//是否收藏
            'zuizao'=>$zuizao,//最早可购买时间
            'Sales'=>$goods['goodssales'] + $goods['invented_sold'],// 商品销量
            'comment_num'=>$comment_num,//评论数
            'comment'=>$pinglun,//评论
            'tag'=>$tag,//tag标签
            'zhekou'=>$zhekou,//商品会员折扣价
            'yuanjia'=>$yuanjia,//商品原价
            'img'=>['image'=>$image,'video'=>$video],//商品视频 轮播图
            'tuijian1'=>$tuijian1,//猜你喜欢 推荐
            'eng_name'=>$goods['goods_englishname'],//商品英文名
            'goods_introduce'=>$is_text_plan?$textPlan:$goods['goods_introduce'],//产品介绍
            'price_include'=>$goods['price_include'],//费用包含
            'price_noinclude'=>$goods['price_noinclude'],//费用不含
            'goods_careful'=>$goods['goods_careful'],//注意事项
            'goods_retreating'=>$goods['goods_retreating'],//退改规则
            'city_id'=>$city['city_id'],//城市id
            'city_name'=>$city['name'],//城市名称
            'goods_status'=>$goods['goods_status'],//城市名称
            'need_confirm'=>$goods['need_confirm'],//是否需要二次确认
            'goodstag'=>$goods['tag_name'],//商品类型
            'currency'=>$currency_code,//外币类型
            'foreign_zhekou'=>$foreign_zhekou,//外币    商品会员折扣价
            'foreign_yuanjia'=>$foreign_yuanjia,//外币    商品原价
            'discount'=>$discoun_per??1,//折扣
            'subTitle'=>$standard['introduce']??'',//副标题
            'customer_content'=>$customer_content,//自定义内容
            'featuredProduct'=>$featuredProduct,
            'activityInfo'=>$activityInfo,
            'selfDriveInfo'=>$selfDriveInfo,
        ];
        $data['allCustomerInfoReq'] = !empty($productInfo['all_customer_req'])?true:false;
        $customer_info_config = $productInfo['customer_info_config']??'';
        $data['customerInfoConfig'] = (new SDModel())->getProductCustomerInfoConfig($customer_info_config);
        $recode=0;
        $status='ok';

        if($goods['show']==2){
            //进行验证
            $code=$goods['code'];
            $viator=new Viator();
            $res=$viator->checkGoods($code);
            if($res['code']==1){//code=1时为验证失败
                $recode=$res['data']['code'];
                $data=$res['data']['msg'];
                $status=$res['data']['msg'];
            }else{
                $goods_res = $res['data'];//验证时取的新数据
                if(!empty($goods_res['bookingQuestions'])){
                    $data['bookingQuestions'] = $goods_res['bookingQuestions'];//增加预约问题数据
                }
            }
        }
        $shu=[
            'code'=>$recode,
            'msg'=>$status,
            'data'=>$data
            ,'member_pcode'=>$this->member_pcode
        ];

        $log[]=[
            '查询details'=>$shu,
        ];
        Log::record($log);

        //增加浏览量
        Request::instance()->post(['secret_code'=>'123']);
        Request::instance()->post(['secret'=>'09a0bbd1c2c2daa157bd8a239b48900f']);
        $request = Request::instance();
        (new Standard())->addGoodsViewCount($request,0,$goods_id,'wap');

        return json_encode($shu);
    }

    //优惠券查询
    public function coupon(){
        header('Access-Control-Allow-Origin:*');
        $m=model('Coupon');
        $goods_id= input('goods_id');
        $member_id= input('member_id');

        //获取用户
//       $member=db('member')->where('wechat_openid',$openid)->find();
        $data=[];
        //获取商品分类
        $classify_id=Db::name('goods')->where(['goods_id'=>$goods_id])->find()['classify_id'];

        //获取优惠券
        $time=time();
        $w['coupon_status']=2;
        $w['open_status']=1;  //公开
        $w['etart_receivetime']=['<',$time];
        $w['end_receivetime']=['>',$time];
        //获取全部类的优惠券
        $findnine=$m->where($w)->where(function ($m){
            $m->where(['coupon_userange'=>999999])->whereOr(['classify_id'=>999999]);
        })
            ->field('coupon_id,coupon_discount,coupon_usecondition,
           etart_usetime,end_usetime,coupon_quantity,coupon_types,receive_limit,coupon_alreadyreceived')
            ->select();
        //获取品类的优惠券
        $findclass=$m->where($w)
            ->where('find_in_set(:id,classify_id)',['id'=>$classify_id])
            ->field('coupon_id,coupon_discount,coupon_usecondition,
           etart_usetime,end_usetime,coupon_quantity,coupon_types,receive_limit,coupon_alreadyreceived')
            ->select();
        //获取商品类的优惠券
        $coupon=$m->where($w)
            ->where('find_in_set(:ids,coupon_userange)',['ids'=>$goods_id])
            ->field('coupon_id,coupon_discount,coupon_usecondition,
           etart_usetime,end_usetime,coupon_quantity,coupon_types,receive_limit,coupon_alreadyreceived')
            ->select();
        if(!empty($findnine)){
            foreach ($findnine as $k){
                array_push($coupon,$k);
            }
        }
        if(!empty($findclass)){
            foreach ($findclass as $k){
                array_push($coupon,$k);
            }
        }
        //判断是否领取
        if(!empty($coupon)){
            foreach ($coupon as $v){
                if ($v['end_usetime']<time()){
                    continue;
                }else{
                    $v['full_reduction']='';
                    //获取优惠券记录
                    $coupondetails=  db('coupondetails')->where('member_id',$member_id)->where('coupon_id',$v['coupon_id'])->count();
                    if($coupondetails==$v['receive_limit']){
                        $v['receive']=2;
                    }else{
                        $v['receive']='';
                    }
                    $v['validityperiod']=date('Y-m-d',$v['etart_usetime']).'---'.date('Y-m-d',$v['end_usetime']);

                    if($v['coupon_types']==1){
                        $v['coupon_discount']=$v['coupon_discount'];
                        $v['full_reduction']='';
                    }else if ($v['coupon_types']==2){
                        $v['full_reduction']= $v['coupon_discount'];
                        $v['coupon_discount']='';
                    }
                    $v['shuliang']=$v['coupon_quantity']-$v['coupon_alreadyreceived'];
                    //新增无限量 对之前为null的进行处理

                    $v['num_types']=empty($v['num_types'])?2:$v['num_types'];
                    if($v['num_types'] == 1){
                        $v['shuliang']=9999;
                    }
                    $data[]=[
                        "coupon_id"=>$v['coupon_id'],
                        "discount"=>$v['coupon_discount'],//折扣
                        "full_reduction"=>$v['full_reduction'],//满减
                        "coupon_usecondition"=>$v['coupon_usecondition'],//使用条件
                        'validityperiod'=>$v['validityperiod'],//有效期
                        "coupon_quantity"=>$v['shuliang'],//数量
                        "receive"=>$v['receive'],//是否已领取判断
                    ];
                }

            }
        }
        $shu=[];
        if ($data){
            $shu=[
                'code'=>0,
                'msg'=>'ok',
                'data'=>$data,

            ];
        }else{
            $shu=[
                'code'=>0,
                'msg'=>'错误',
                'data'=>''
            ];
        }

        return json_encode($shu);
    }

    //套餐选择
    public function package(){
        $post=  request()->post();
        $goods_id= $post['goods_id'];
        $member_id=!empty( $post['member_id'])? $post['member_id']:'';
        $gradeCode=!empty( $post['gradeCode'])? $post['gradeCode']:'';
        $specs_id=!empty( $post['specs_id'])? $post['specs_id']:0;
        $data1=[];
        $data=[];
        $mk_shuzu='';
        $shuzu='';
        $discoun_per='';

        $exchange= db('exchange')->where('currency_code',"USD")->find();//汇率
        $goods=db('goods')->where('goods_id',$goods_id)->find();

        //产品价格替换
        $product_id = '';
        $product_price_exists = 0;//是否存在产品价格
        //存在产品时
        if(!empty($goods['goods_tcode']) && $goods['goods_tcode']!==''){
            $product = db("product")->where("item_num",$goods['goods_tcode'])->field("id,price_section")->find();
            if(!empty($product)){
                $product_id = $product['id'];
                $dailyprice = db("product_dailyprice")->where("product_id",$product_id)->find();
                if(!empty($dailyprice)){
                    $product_price_exists = 1;//存在产品设置价格
                }
            }
        }

        if (empty($goods)){
            $shu=[
                'code'=>101,
                'msg'=>'参数错误',
            ];
            echo json_encode($shu);die();
        }

        if (!empty($member_id)){
            $discoun_per_arr = $this->get_discoun_per($member_id);//获取折扣集
            //该类型商品的折扣率
            $discoun_per = isset($discoun_per_arr[$goods['classify_id']]) ? $discoun_per_arr[$goods['classify_id']] : '';
        }

        $kaishi1=$goods['starttime'];
        $jieshu=$goods['endtime']+86399;
        if ($jieshu < time()){
            db('goods')->where('goods_id',$goods_id)->update([
                'goods_status'=> '2'
            ]);
            $shu=[
                'code'=>0,
                'msg'=>'商品超过售卖时间已下架~~~~',
                'error'=>'101',
                'data'=>''
            ];
            return json_encode($shu);
        }

        if($goods['show']==2){
            $shi=strtotime($this->getNextMonthDays(date('Y-m-d',time())));
        }else{
            $shi=strtotime($this->getNextMonthDays_myself(date('Y-m-d',time())));
        }
        if ($kaishi1>$shi){
            $shu=[
                'code'=>0,
                'msg'=>'商品开始售卖时间太遥远~~~~',
                'error'=>'101',
                'data'=>''
            ];
            return json_encode($shu);
        }

        if(!empty($goods['code']) && $goods['show']== 2){
            //获取viator的折扣
            $discoun_num=1;
            $discoun_viator=Db::name('viator_discount')->where(['id'=>1,'status'=>1])->find();
            if(!empty($discoun_viator)){
                $discoun_num = $discoun_viator['discount_num'];
            }

            $Viator= new Viator();

            $jia=[];
            $data=[];
            $d=[];
            $data1= cache($goods['code'].'price');

            if(empty($gradeCode)){
                $data1=array_shift($data1);
            }else{
                $data1=isset($data1[$gradeCode])?$data1[$gradeCode]:'';
            }
            $redaSpecs=cache($goods['code'].'type');
            $eto_list=[
                'Adult'=>'成人',
                'Child'=>'儿童',
                'Infant'=>'婴儿',
                'Youth'=>'青年',
                'Senior'=>'老年人',
                '成年人'=>'成年人',
                '儿童'=>'儿童',
                '婴儿'=>'婴儿'
            ];
            if(empty($data1)){
                $data['kbx']['riqijiage']='';
            }else{
                foreach ($data1 as $s=>$v){
                    $d[$s]['shijian']=$v['bookingDate'];
                    $d[$s]['shuliang']=999;
                    foreach ($v['ageBands'] as $l=>$k){
                        $person_price= ceil($exchange['exchange_rate']*$k['price']*$discoun_num*100)/100;

                        if (!empty($discoun_per)){
                            $person_price= ceil($discoun_per*$person_price*100)/100;
                        }
                        $jia[]=$k['price'];
                        $description_name = isset($eto_list[$k['description']]) ? $eto_list[$k['description']] : $k['description'];
                        $d[$s]['Person'][$l]=[
                            "person_id"=>$k['bandId'],
                            "person_price"=>$person_price,
                            "person_num"=>999,
                            "person_name"=>$k['age'].'岁'.$description_name,
                            "max"=>$k['max'],
                            "min"=>$k['min'],
                        ];
                    }

                    $min= max($jia);
                    $d[$s]['jiage']=ceil($min*$exchange['exchange_rate']*$discoun_num*100)/100;
                    if (!empty($discoun_per)){
                        $d[$s]['jiage']= ceil($discoun_per*$d[$s]['jiage']*100)/100;
                    }
                }
                foreach ($d as $v){
                    $data['kbx']['riqijiage'][]=$v;
                }
            }


            //By Suley
            //修改过的自定义套餐名称
            $where_name['code'] = $goods['code'];
            $specsName = db('specsname')->where($where_name)->select();
            $nameArr = array();
            if(!empty($specsName)){
                foreach ($specsName as $k_name=>$v_name){
                    $nameArr[$v_name['grade_code']] = $v_name['new_name'];
                }
            }

            //套餐修改
            foreach ($redaSpecs as $a){
                if(isset($nameArr[$a['gradeCode']])){
                    $a['specs_name'] = $nameArr[$a['gradeCode']];//使用修改过的自定义套餐名称
                }
                $data['kbx']['specs'][]=$a;
            }
            $data['kbx']['typesource']='viator';
            $shu=[
                'code'=>0,
                'msg'=>'ko',
                'data'=>$data
            ];

            echo json_encode($shu);die;
        }

        if($product_price_exists==1){
            $sp = db('product_package')
                ->where('product_id',$product_id)
                ->where('status',1)
                ->field('id,name')
                ->select();
            foreach ($sp as $s){
                $ce = db('product_specs')
                    ->where('package_id',$s['id'])
                    ->where('status', 1)
                    ->select();
                if (!empty($ce)){
                    $s['gradeCode']='';
                    $s['code']='';
                    $data['specs'][]=$s;
                }
            }
        }else{
            $sp=model('Specs')
                ->where('goods_id',$goods_id)
                ->where('specs_status',1)
                ->where('specs_types',1)
                ->field('specs_id,specs_name,specs_types')
                ->select();
            foreach ($sp as $s){
                $ce = model('Person')
                    ->where('specs_id',$s['specs_id'])
                    ->where('person_status', 1)
                    ->select();
                if (!empty($ce)){
                    $s['gradeCode']='';
                    $s['code']='';
                    $data['specs'][]=$s;
                }
            }
        }
        if (!empty($specs_id)){
            //获取活动
            $mk=model('Marketing')
                ->where('goods_id',$goods_id)
                ->where('mk_status',1)
                ->find();

            //商品售卖开始时间结束时间
            $kaishi=$goods['starttime'];
            $jieshu=$goods['endtime']+86399;

            $tian=ceil(($jieshu-$kaishi)/60/60/24);
            //活动开始结束时间
            $mk_kaishi=$mk['mk_starttime'];
            $mk_jieshu=$mk['mk_endtime'];
            $mk_tian=ceil(($mk_jieshu-$mk_kaishi)/60/60/24);
            //判断是否是活动
            $shuliang=0;
            $Person=[];

            //基本弃用
            if (!empty($mk)||$mk==true){
                $mk_specs_id=  db('specs')->where('pid',$specs_id)->where('specs_status',1)->select();
                foreach ($mk_specs_id as $v){
                    $Person1 = model('Person')
                        ->where('specs_id',$v['specs_id'])
                        ->where('person_status', 1)
                        ->field('person_id,person_name,person_num,person_price,minorder_num')
                        ->select();

                    foreach ($Person1 as $g){
                        $Person[]=$g;
                    }
                }

                $min=0;
                if (!empty($Person)){
                    if (!empty($discoun_per)){
                        foreach ($Person as $k=>$v){
                            $price[]=$v['person_price'];
                            $Person[$k]['person_price']= ceil($v['person_price']*$discoun_per*100)/100;
                            $shuliang+=(int)$v['person_num'];
                        }
                    }else{
                        foreach ($Person as $k=>$v){
                            $price[]=$v['person_price'];
                            $Person[$k]['person_price']= ceil($v['person_price']*100)/100;
                            $shuliang+=(int)$v['person_num'];
                        }
                    }

                    $min= min($price);
                    if (!empty($discoun_per)){
                        $min = ceil(($min*$discoun_per)*100)/100;
                    }
                }

                $g=0;
                for ($i=0;$i<$mk_tian;$i++){
                    $mk_shuzu[$i]=[
                        'shijian'=>date('Y-m-d',$mk_kaishi+$g),
                        'jiage'=>$min,
                        'Person'=>$Person
                    ];
                    $g+=86400;
                }
            }
            //基本弃用

            $Persons=model('Person')
                ->where('specs_id',$specs_id)
                ->where('person_status',1)
                ->field('person_id,person_price,person_num,person_name,minorder_num')
                ->select();
            $shuliang1=0;
            $z_min=0;
            if (!empty($Persons)){
                if(empty($discoun_per)){
                    $discoun_per_person = 1;
                }else{
                    $discoun_per_person = $discoun_per;
                }
                foreach ($Persons as $k=>$v){
                    $pricea[]=$v['person_price'];
                    $Persons[$k]['person_price']= ceil($v['person_price']*$discoun_per_person*100)/100;
                    $shuliang1+=(int)$v['person_num'];
                }
                $z_min= min($pricea);
                if (!empty($discoun_per)){
                    $z_min=  ceil($z_min*$discoun_per*100)/100;
                }
            }

            $s=0;
            for ($i=0;$i<$tian;$i++){
                $shuzu[$i]=[
                    'shijian'=>date('Y-m-d',$kaishi+$s),
                ];
                $s+=86400;
            }

            $where['isdelete']=0;
            $where['refund_status']=0;//
            $where['order_status']=[['NEQ',6],['NEQ',7,'or']];//订单查询条件

            $xin='';
            foreach ($shuzu as $k=>$v){
                if ($v['shijian']>date('Y-m-d',(time()-86400))){
                    if ($v['shijian']<$shi){//获取数据限制 最长6个月
                        $xin[$k]['shijian']=$v['shijian'];
                        $maiqu= db('order')
                            ->where('goods_id',$goods_id)
                            ->where($where)
                            ->where('travel_date',$v['shijian'])
                            ->select();
                        $xin[$k]['shuliang']=$shuliang1;
                        $xin[$k]['Person']=$Persons;
                        $yimai=0;
                        $person_num=0;
                        $renshu2=[];
                        foreach ($maiqu as $s){//循环已有订单
                            $renshu=0;
                            if ($v['shijian']===$s['travel_date']){
                                $shengyu=db('orderperson')->where('order_id',$s['order_id'])->select();//获取订单详情
                                if(!empty($shengyu)){
                                    foreach ($shengyu as $ff){
                                        $renshu2[]=[//组装每一天订单下面的规格详情
                                            'person_id' => $ff['person_id'],
                                            'person_price' => ceil($ff['person_price']*100)/100,
                                            'person_num' =>$ff ['person_num'],
                                            'person_name' => $ff['person_name'],
                                            'chuxing' => $ff['chuxing'],
                                            'max'=>0,
                                            'min'=>0,
                                        ];
                                    }
                                }
                            }
                        }
                        if (!empty($renshu2)){
                            $new = array();
                            foreach($renshu2 as $row){ //对每一天的订单规格详情进行去重 数量相加的操作
                                if(isset($new[$row['person_id']])){
                                    $new[$row['person_id']]['person_num'] += $row['person_num'];
                                }else{
                                    $new[$row['person_id']] = $row;
                                }
                            }

                            foreach ($Persons as $f=>$g){//计算商品剩余量
                                foreach ($new as $kk=>$hh){
                                    if ($v['shijian']==$hh['chuxing']) {//判断时间
                                        if ($g['person_id'] == $hh['person_id']){//判断相等的详情id
                                            $yimai+=$hh['person_num'];
                                            $xin[$k]['Person'][$f] = [
                                                'person_id' => $g['person_id'],
                                                'person_price' =>  ceil($g['person_price']*100)/100,
                                                'person_num' => $g['person_num'] - $hh['person_num'],
                                                'person_name' => $g['person_name'],
                                                'max'=>0,
                                                'min'=>0,
                                            ];
                                        }
                                    }
                                }
                            }
                        }
                        $xin[$k]['shuliang']=$shuliang1-$yimai;
                        $xin[$k]['jiage']=ceil($z_min*100)/100;
                        if (!empty($mk_shuzu)){//活动判断
                            foreach ($mk_shuzu as $t){
                                if ($v['shijian']==$t['shijian']){
                                    $maiqu= db('order')
                                        ->where('goods_id',$goods_id)
                                        ->where($where)
                                        ->where('travel_date',$v['shijian'])
                                        ->select();

                                    $xin[$k]['Person']=$t['Person'];
                                    $xin[$k]['shuliang']=$shuliang;
                                    $yimai=0;
                                    foreach ($maiqu as $s){
                                        if ($t['shijian']===$s['travel_date']){
                                            $shengyu=db('orderperson')->where('order_id',$s['order_id'])->select();
                                            if(!empty($shengyu)){
                                                foreach ($shengyu as $ff){
                                                    $renshu2[]=[
                                                        'person_id' => $ff['person_id'],
                                                        'person_price' => ceil($ff['person_price']*100)/100,
                                                        'person_num' =>$ff ['person_num'],
                                                        'person_name' => $ff['person_name'],
                                                        'chuxing' => $ff['chuxing'],
                                                        'max'=>0,
                                                        'min'=>0,
                                                    ];
                                                }
                                            }
                                        }
                                    }
                                    if (!empty($renshu2)) {
                                        $new = array();
                                        foreach ($renshu2 as $row) {
                                            if (isset($new[$row['person_id']])) {
                                                $new[$row['person_id']]['person_num'] += $row['person_num'];
                                            } else {
                                                $new[$row['person_id']] = $row;
                                            }
                                        }

                                        foreach ($t['Person'] as $f => $g) {
                                            foreach ($new as $kk => $hh) {
                                                if ($v['shijian'] == $hh['chuxing']) {
                                                    if ($g['person_id'] == $hh['person_id']) {
                                                        $yimai += $hh['person_num'];
                                                        $xin[$k]['Person'][$f] = [
                                                            'person_id' => $g['person_id'],
                                                            'person_price' => ceil($g['person_price']*100)/100,
                                                            'person_num' => $g['person_num'] - $hh['person_num'],
                                                            'person_name' => $g['person_name'],
                                                            'max'=>0,
                                                            'min'=>0,
                                                        ];
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    $xin[$k]['shuliang']=$shuliang-$yimai;
                                    $xin[$k]['jiage']=$t['jiage'];
                                }
                            }
                        }
                    }
                }
            }
            $xin=  array_values($xin);
            $data['riqijiage']=$xin;
        }
        $data1['kbx']=$data;
        $data1['goods']=$goods;
        $data1['kbx']['typesource']='myself';

        $shu=[
            'code'=>0,
            'msg'=>'ko',
            'data'=>$data1,
            'member_pcode'=>$this->member_pcode
        ];

        return json_encode($shu);

    }

    public function getNextMonthDays($date){
        $firstday = date('Y-m-01', strtotime($date));
        $lastday = strtotime("$firstday +6 month -1 day");
        $day_lastday = date('d', $lastday); //获取下个月份的最后一天
        $day_benlastday = date('d', strtotime("$firstday +1 month -1 day")); //获取本月份的最后一天
        //获取当天日期
        $Same_day = date('d', strtotime($date));
        //判断当天是否是最后一天   或 下月最后一天 等于 本月的最后一天
        if($Same_day == $day_benlastday||$day_lastday == $Same_day){
            $day = $day_lastday;
        }else{
            $day = $Same_day;
        }
        $day = date('Y',$lastday).'-'.date('m',$lastday).'-'.$day;
        return $day;
    }

    //自营商品  时间增至10个月
    public function getNextMonthDays_myself($date){
        $firstday = date('Y-m-01', strtotime($date));
        $lastday = strtotime("$firstday +10 month -1 day");
        $day_lastday = date('d', $lastday); //获取下个月份的最后一天
        $day_benlastday = date('d', strtotime("$firstday +1 month -1 day")); //获取本月份的最后一天
        //获取当天日期
        $Same_day = date('d', strtotime($date));
        //判断当天是否是最后一天   或 下月最后一天 等于 本月的最后一天
        if($Same_day == $day_benlastday||$day_lastday == $Same_day){
            $day = $day_lastday;
        }else{
            $day = $Same_day;
        }
        $day = date('Y',$lastday).'-'.date('m',$lastday).'-'.$day;

        return $day;
    }



    //*******【首页改版API】******************************************************************

    //当前城市下（目的地）商品列表  接口API
    public function CurrentCityGoods(){
        $post= request()->post();
        $lat = $post['lat'];
        $lng = $post['lng'];
        $member_id = isset($post['member_id'])?$post['member_id']:0;//用户id

        //按照经纬度匹配城市
        $GeoHash = new GeoHash();
        $city = $GeoHash->getCity($lat,$lng);

        if(empty($city)){
            $shu=[
                'code'=>0,
                'msg'=>'未匹配到当地城市',
            ];
            return json_encode($shu);
        }

        $m = new M();
        $where['city_id'] = $city['city_id'];
        $where['goods_status'] = 1;
        //是否拼团产品 拼团不显示
        $map['is_group']='0';
        $where['orderType'] = 'Ticket_FIT';
        $date = $m->where($where)
                ->field('goods_id as id,city_id,goods_name as name,classify_id,
                    goods_image,small_image as img ,price,goods_englishname as eng_name,starttime,endtime,
                    recommend,popular,updating,goodssales,invented_sold,show')
                ->order('goodssales desc')->limit(5)->select();
        $shu = $this->OrderData($date,$member_id);

        $shu['city'] = $city;

        return json_encode($shu);
    }

    //爆款商品列表  接口API
    public function hotGoods(){
        $post= request()->post();
        $member_id = isset($post['member_id'])?$post['member_id']:0;//用户id
        $m = new M();

        $setData = db("indexset")->where("id",2)->find();
        $id_str = $setData['id_str'];
        $idArr = explode(",",$id_str);
        $data = [];
        foreach ($idArr as $k=>$v) {
            $date = $m
                ->where("goods_id",$v)
                ->field('goods_id as id,city_id,goods_name as name,classify_id,
                            goods_image,small_image as img ,price,goods_englishname as eng_name,starttime,endtime,
                            recommend,popular,updating,goodssales,invented_sold,show,goods_tcode')
                ->find();
            $data[] = $date;
        }

        $shu = $this->OrderData($data,$member_id);
        return json_encode($shu);
    }

    //当季商品列表  接口API
    public function seasonGoods(){
        $post = request()->post();
        $member_id = isset($post['member_id'])?$post['member_id']:0;//用户id
        $m = new M();

        $setData = db("indexset")->where("id",1)->find();
        $id_str = $setData['id_str'];
        $idArr = explode(",",$id_str);

        $data = [];
        foreach ($idArr as $k=>$v) {
            $date = $m
                ->where("goods_id",$v)
                ->field('goods_id as id,city_id,goods_name as name,classify_id,
                            goods_image,small_image as img ,price,goods_englishname as eng_name,starttime,endtime,
                            recommend,popular,updating,goodssales,invented_sold,show,goods_tcode')
                ->find();
            $data[] = $date;
        }

        $shu = $this->OrderData($data,$member_id);
        return json_encode($shu);
    }

    //wap格式化返回 商品数据格式
    public function OrderData($date,$member_id)
    {
        //查询city对应名称
        $cityArr = Db::name('city')->field("id,name,groupid")->select();
        $cityNameArr = [];
        $countryNameArr = [];
        foreach ($cityArr as $city_v) {
            if(empty($city_v['groupid'])){
                $countryNameArr[$city_v['id']] = $city_v['name'];
            }else{
                $cityNameArr[$city_v['id']] = [
                    'name'=>$city_v['name'],
                    'groupid'=>$city_v['groupid'],
                ];
            }
        }
        //获取viator的折扣
        $discoun_num='';
        $discoun_viator=Db::name('viator_discount')->where(['id'=>1,'status'=>1])->find();
        if(!empty($discoun_viator)){
            $discoun_num = $discoun_viator['discount_num'];
        }

        $exchange= db('exchange')->where('currency_code',"USD")->find();//汇率
        $discoun_per_arr = array();
        if(!empty($member_id)){
            $discoun_per_arr = $this->get_discoun_per($member_id);//获取折扣集
        }
        $d=[];
        $collection=0;
        $qujian1='';
        if (!empty($date)){
            foreach ($date as $k=>$v){
                //该类型商品的折扣率
                $discoun_per = isset($discoun_per_arr[$v['classify_id']]) ? $discoun_per_arr[$v['classify_id']] : '';
                if(!empty($v['price'])){
                    //viator 商品折扣判断
                    if($v['show'] == 2 && !empty($discoun_num)){
                        $v['price']=$v['price']*$discoun_num;
                    }

                    $yuanjia='';
                    $qujian1=ceil($v['price']*$exchange['exchange_rate']*100)/100;
                    if(!empty($discoun_per)){
                        $yuanjia=ceil($v['price']*$exchange['exchange_rate']*100)/100;
                        $qujian1=ceil($discoun_per*$qujian1*100)/100;
                    }
                }else{
                    //是否存在关联产品
                    $product = db('product')->where('item_num',$v['goods_tcode'])->field('id,currency,new_price_flag,base_price_mode')->find();
                    if(!empty($product['base_price_mode']) && $product['base_price_mode']>0){
                        //先以产品价格为准
                        $today = date('Y-m-d');
                        $product_cost = db("product_base_dailyprice pd")
                            ->join('product_base_specs ps','ps.id=pd.specs_id','left')
                            ->field("min(pd.price*pd.minorder_num) as minprice,max(pd.price*pd.minorder_num) as maxprice")
                            ->where(['product_id'=>$product['id'],'total_cost'=>['gt',0],'time'=>['gt',$today]])
                            ->find();
                        $min1 = round($product_cost['minprice']??0);
                        $max1 = round($product_cost['maxprice']??0);
                        //关联产品的价格问题
                        if(!empty($product['currency']) && $exchangeRate = db('exchange')->where("currency_code",$product['currency'])->find()){
                            $local_exchange = $exchangeRate['exchange_rate']??1;//默认人民币汇率
                            $max1 = !empty($max1)?ceil(round($max1)*$local_exchange):0;
                            $min1 = !empty($min1)?ceil(round($min1)*$local_exchange):0;
                        }
                    }elseif(!empty($product['new_price_flag']) && $product['new_price_flag']>0){
                        //先以产品价格为准
                        $today = date('Y-m-d');
                        $priceList = db('product_dailyprice')->where(['product_id'=>$product['id'],'time'=>['gt',$today]])->column('price');
                        $max1 = !empty($priceList)?max($priceList):0;
                        $min1 = !empty($priceList)?min($priceList):0;
                    }else{
                        $priceList = db('Specs')->alias('s')
                            ->where('s.goods_id',$v['id'])
                            ->where('s.specs_status','1')
                            ->join('Person p','s.specs_id=p.specs_id')
                            ->where('p.person_status','1')
                            ->column('p.person_price');
                        $max1 = !empty($priceList)?max($priceList):0;
                        $min1 = !empty($priceList)?min($priceList):0;
                    }

                    //viator 商品折扣判断
                    if($v['show'] == 2 && !empty($discoun_num)){
                        $max1= ceil($discoun_num * $max1 * 100)/100;
                        $min1 = ceil($discoun_num * $min1 * 100)/100;
                    }

                    if (!empty($discoun_per)){
                        $yuanjia=$min1.'~'.$max1;
                        $qujian1=  ceil($min1*$discoun_per*100)/100 .'~'.ceil($max1*$discoun_per*100)/100;
                        if ($max1==$min1  || $min1=='0.00'){
                            $qujian1=ceil($max1*$discoun_per*100)/100;
                            $yuanjia=$max1;
                        }
                    }else{
                        $yuanjia='';
                        $qujian1=  $min1.'~'.$max1;
                        if ($max1==$min1 || $min1=='0.00'){
                            $qujian1=ceil($max1*100)/100;
                            $yuanjia='';
                        }
                    }

                }
                if (!empty($member_id)){
                    $collection=db('collection')->where('goods_id',$v['id'])->where('collection_types',1)->where('member_id',$member_id)->find();
                    if (!empty($collection)){
                        $collection=1;
                    }
                }
                if (!empty($v['img'])){
                    $image=explode(',',$v['img']);
                    $image=$image[0]==''?$image[1]:$image[0];
                }else{
                    $image=explode(',',$v['goods_image']);
                    $image= array_filter($image);
                    $image=array_values($image);
                    $image=isset($image[0]) ? $image[0] : '';
                }
                if (time()>$v['starttime'] && time()<$v['endtime'] ){
                    $zuizao='今天';
                }else if(time()<$v['starttime']){
                    $zuizao=date('m-d',$v['starttime']);
                }else{
                    $zuizao='未知';
                }

                //评论数
                $where_comment['goods_id'] = $v['id'];
                $comment_res = Db::name("comment")->where($where_comment)->field("comment_id")->select();
                $comment_num = count($comment_res);

                if(isset($v['city_id']) && $v['city_id']!==''){
                    $cityName = $cityNameArr[$v['city_id']]['name']??'';
                    $countryName = $countryNameArr[$cityNameArr[$v['city_id']]['groupid']]??'';
                }else{
                    $cityName = '';
                    $countryName = '';
                }

                if (empty($qujian1)&&empty($yuanjia)){
                    $tui1=[];
                }else{
                    $tui1=[
                        'goods_id'=>$v['id'],
                        'city_name'=>$cityName,
                        'country_name'=>$countryName,
                        'recommend'=>$v['recommend'],
                        'popular'=>$v['popular'],
                        'name'=>$v['name'],
                        'jiage'=>$qujian1,
                        'image'=>$image,
                        'eng_name'=>$v['eng_name'],
                        'zuizao'=>$zuizao,
                        'collection'=>$collection,
                        'yuanjia'=>$yuanjia,
                        'updating'=>$v['updating'],
                        'comment_num'=>$comment_num,
                        'order_num'=>$v['goodssales'] + $v['invented_sold'],
                    ];
                }
                if(!empty($tui1)){
                    $d['goods'][]=$tui1;
                }
            }

            $shu=[
                'code'=>0,
                'msg'=>'请求成功',
                'data'=> $d,
                'member_pcode'=>$this->member_pcode
            ];
        }else{
            $shu=[
                'code'=>101,
                'msg'=>'暂无更多数据',
            ];
        }

        return $shu;
    }

    //获取用户的 折扣率集
    public function get_discoun_per($member_id=159){
        //查询用户
        $member = db('member')->where('member_id',$member_id)->find();

        $all_per_arr = array();
        if($member['member_type_id']==1){
            return $all_per_arr;
        }

        $classify_info = Db::name('classify')->where("classify_status",1)->select();
        //加入包车和接送机
        $classify_info[] = array("classify_id"=>304,"classify_name"=>"接送机","classify_status"=>1,"creattime"=>0,"updatetime"=>0);
        $classify_info[] = array("classify_id"=>305,"classify_name"=>"包车","classify_status"=>1,"creattime"=>0,"updatetime"=>0);
        $classArr = array();
        foreach ($classify_info as $v) {
            $classArr[] = $v['classify_id'];
        }

        $where['member_type_id'] = $member['member_type_id'];
        $where['type_status'] = 1;
        $discoun_per = db('member_type')->where($where)->find();
        if(!empty($discoun_per)){
            //拆分 折扣率字符串
            $commission_per_list = $discoun_per['discoun_per_list'];
            if($commission_per_list && $commission_per_list!==''){
                $commission_per_arr = explode(",",$commission_per_list);
                foreach ($commission_per_arr as $per_value){
                    $per_arr = explode("_",$per_value);
                    $per_classify_id = $per_arr[0];
                    if(!in_array($per_classify_id,$classArr)){
                        continue;
                    }
                    $per = $per_arr[1];
                    $all_per_arr[$per_classify_id] = $per;
                }
            }
        }

        return $all_per_arr;
    }

    //获取商品外币价格
    public function changeShowPrice()
    {
        $lat =  input('lat');
        $lng =  input('lng');
        $yuanjia =  input('yuanjia');
        $zhekou =  input('zhekou');

        $KbxOther = new KbxOther();
        $res = $KbxOther->getCountry($lat,$lng);

        $data = [];
        if($res['status']==0){
            $country = $res['result']['addressComponent']['country_code_iso'];
            if($country=='USA'){//美国
                $currency_code = "USD";
            }elseif($country=='CAN'){//加拿大
                $currency_code = "CAD";
            }else{//其他地区退出
                $shu=[
                    'code'=>400,
                    'msg'=>"not in usa or cannada",
                    'data'=>$data
                ];
                return json_encode($shu);
            }

            $exchangeArr = Db::name("exchange")->where("currency_code",$currency_code)->find();//汇率
            $local_exchange = $exchangeArr['exchange_rate'];//当地汇率    美元/加元

            $yuanjiaArr = explode("~",$yuanjia);
            $zhekouArr = explode("~",$zhekou);

            if(count($yuanjiaArr)>1){
                $foreign_yuanjia_min = ceil(($yuanjiaArr[0]/$local_exchange)*100)/100;
                $foreign_yuanjia_max = ceil(($yuanjiaArr[1]/$local_exchange)*100)/100;
                $foreign_yuanjia = $foreign_yuanjia_min."~".$foreign_yuanjia_max;
            }else{
                $foreign_yuanjia = ceil(($yuanjia/$local_exchange)*100)/100;
                if($foreign_yuanjia==0){
                    $foreign_yuanjia = '';
                }
            }

            if(count($zhekouArr)>1){
                $foreign_zhekou_min = ceil(($zhekouArr[0]/$local_exchange)*100)/100;
                $foreign_zhekou_max = ceil(($zhekouArr[1]/$local_exchange)*100)/100;
                $foreign_zhekou = $foreign_zhekou_min."~".$foreign_zhekou_max;
            }else{
                $foreign_zhekou = ceil(($zhekou/$local_exchange)*100)/100;
            }

            $data = [
                'currency'=>$currency_code,//外币类型
                'foreign_zhekou'=>$foreign_zhekou,//外币    商品会员折扣价
                'foreign_yuanjia'=>$foreign_yuanjia,//外币    商品原价
            ];

            $shu=[
                'code'=>0,
                'msg'=>"ok",
                'data'=>$data
            ];
        }else{
            $shu=[
                'code'=>401,
                'msg'=>"Api Error",
                'data'=>$data
            ];
        }

        return json_encode($shu);
    }

    //按主题查询商品list
    public function getThemeGoods(){
        $post = request()->post();
        $member_id = isset($post['member_id'])?$post['member_id']:0;//用户id
        $theme_id = isset($post['theme_id'])?$post['theme_id']:0;//主题id

        $m = new M();

        $themeData = db("theme")
            ->alias('t')
            ->join('attachment a' ,'t.thumb1=a.id',"left")
            ->where("t.id",$theme_id)
            ->field("t.*,a.filepath as background")
            ->find();

        $tag_str = $themeData['tag_id'];
        $tagArr = explode(",",$tag_str);
        $field = "goods_id as id,city_id,goods_name as name,classify_id,
                goods_image,small_image as img ,price,goods_englishname as eng_name,starttime,endtime,
                g.recommend,g.popular,g.updating,g.goodssales,g.invented_sold,g.`show`";
        $data = (new TModel())->getThemeSortGoods($themeData,$field);
        $data = $data->select();
//        var_dump($data->toArray());exit;
        $shu = $this->OrderData($data,$member_id);

        $shu['data']['theme'] = $themeData;

        return json_encode($shu);
    }

    //20200203 wtt
    public function searchConditions()
    {
        $data['types'] = db('classify')
            ->where(['classify_status'=>1])
            ->field('classify_id,classify_name')
            ->select();
        $data['days'] = [
            '1'=>'1日游',
            '2'=>'2日游',
            '3'=>'多日游'
        ];
        $data['service_languages'] = [
            '1'=>'英文',
            '2'=>'中文'
        ];
        return json_encode(['code'=>200,'msg'=>'success','data'=>$data]);
    }

}